package com.showsu.editor.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description: 重试工具
 * @Date: Created in 7:29 下午 2023/11/16
 * @Modified By:
 */
@Slf4j
public class RetryUtils {

    /**
     * 重试。这个接口专用于调用外部数据接口，发现重试全部失败的时候短信告警。
     * @param callable callable方法
     * @param loop 重试次数
     * @param retryTime 间隔时间(毫秒)
     * @return 成功信息
     */
    public static String retry(Callable<String> callable, int loop, int retryTime) {
        String successMsg = null;
        while (loop > 0) {
            loop--;
            try {
                successMsg = callable.call();
                if (StringUtils.isNotBlank(successMsg)) {
                    break;
                }
            } catch (Exception e) {
                log.error("RetryUtils.retry(..) error, loop:{}, retryTime:{}", loop, retryTime, e);
            }
            try {
                Thread.sleep(retryTime);
            } catch (InterruptedException e) {
                log.error("RetryUtils.retry(..) sleep error, loop:{}, retryTime:{}", loop, retryTime, e);
            }
        }
        if (StringUtils.isBlank(successMsg)) {
            log.error("RetryUtils.retry(..) 多次 仍然失败，结束！", loop);
        }
        return successMsg;
    }

    /**
     * 重试
     * @param callable callable方法
     * @param loop 重试次数
     * @param retryTime 间隔时间(毫秒)
     * @return 成功信息
     */
    public static <T> T retryT(Callable<T> callable, int loop, int retryTime) {
        T successMsg = null;
        while (loop > 0) {
            loop--;
            try {
                successMsg = callable.call();
                if (successMsg!=null) {
                    break;
                }
            } catch (Exception e) {
                log.error("RetryUtils.retry(..) error, loop:{}, retryTime:{}", loop, retryTime, e);
            }
            try {
                Thread.sleep(retryTime);
            } catch (InterruptedException e) {
                log.error("RetryUtils.retry(..) sleep error, loop:{}, retryTime:{}", loop, retryTime, e);
            }
        }
        if (successMsg==null) {
            log.error("RetryUtils.retry(..) 多次 仍然失败，结束！", loop);
        }
        return successMsg;
    }
}
